<script setup>
import axios from '../../utils/request';
import { reactive, ref } from 'vue'
 
import {useRouter} from 'vue-router'

import {userStore} from '../../stores/user'
import qs from 'qs';
import {ElNotification,ElMessageBox,ElMessage} from 'element-plus'

const router=useRouter();
const stores =userStore();

const formSize = ref('default')
const ruleFormRef=ref() //创建dom的引用
const ruleForm=reactive({
  username:'admin',
    password:'123456'
})

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 18, message: '长度为3-18', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3,max:50, message: '密码长度为6-12', trigger: 'blur' }
    ]
})
 
function dologin(){
    ruleFormRef.value.validate(async(valid) => {
    if (valid) {
 
      //security 登录  
     // let url ="/login?username="+ruleForm.userName+ "&password="+ruleForm.password;
     let url = '/login?'+qs.stringify(ruleForm);
     console.log(url)
     let {data} =await axios.post(url);
 
     if(data.code!==200){
        ElMessage.error("账号或者密码错误,"+data.msg)
     }else{      
        //存token | username   ->pinia  
        stores.setToken(data.data.authorzation)
        stores.setUsername(data.data.username) 
        //跳转
        router.push("/home")
     }
 

     
    } else {
      ElMessage.error('认证失败')
      return false
    }
  })
}
</script>

<template>
    <div class="loginContainer">
      <h1>登录页面 {{stores.num}} </h1>
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dologin(ruleFormRef)"
          >登录</el-button >
        <el-button>忘记密码</el-button>
      </el-form-item>
    </el-form>
    </div>
</template>

<style>
  .loginContainer{
    width: 500px;
    background: white;
    border-radius: 5px;
    position: absolute;
    padding: 15px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
</style>